//
//  CustomRefreshHeader.swift
//  Employee
//
//  Created by swordjoy on 2017/3/30.
//  Copyright © 2017年 remotevillage. All rights reserved.
//

import UIKit
import MJRefresh

class CustomRefreshHeader: MJRefreshHeader {
  
  fileprivate var contentV: UIView!
  fileprivate var loadingImageV: UIImageView!
  fileprivate var loadingLabel: UILabel!
  fileprivate var fromTransform: CGAffineTransform!
  
  override func prepare() {
    super.prepare()
    
    mj_h = 44
    
    create()
    
    fromTransform = self.loadingImageV.transform.rotated(by: .pi / 2)
    
  }
  
  override func placeSubviews() {
    super.placeSubviews()
    
    contentV.frame = CGRect(x: 0, y: 0, width: 120, height: 50)
    contentV.center.x = center.x
    
    loadingImageV.frame = CGRect(x: 0, y: 0, width: 15, height: 15)
    loadingImageV.center.y = contentV.center.y
    
    loadingLabel.frame = CGRect(x: 20, y: 0, width: 100, height: 20)
    loadingLabel.center.y = contentV.center.y
    
  }
  
  override var state: MJRefreshState {
    didSet {
      if oldValue ==  state { return }
      super.state = state
      
      switch state {
      case .idle:
        stopAnimate()
      case .pulling:
        stopAnimate()
      case .refreshing:
        startAnimate()
      default: break
      
      }
    }
  }
  
}

// MARK: - fileprivate

extension CustomRefreshHeader {
  
  fileprivate func animate(with tag: Bool) {
    
    UIView.animate(withDuration: 0.11, animations: {
      self.loadingImageV.transform = CGAffineTransform(rotationAngle: .pi / 2)
    }) { (true) in
      if tag {
        self.animate(with: tag)
      }
    }
    
  }
  
  fileprivate func startAnimate() {
    
    let animation = CABasicAnimation(keyPath: "transform.rotation.z")
    animation.toValue = Double.pi * 2.doubleValue
    animation.duration = 0.28
    animation.isCumulative = true
    animation.repeatCount = Float(INT_MAX)
    loadingImageV.layer.add(animation, forKey: "animation")
    
  }
  
  fileprivate func stopAnimate() {
  
    loadingImageV.layer.removeAllAnimations()
    
  }
  
  
  
  fileprivate func create() {
    
    contentV = UIView()
    addSubview(contentV)
    contentV.backgroundColor = UIColor.clear
    
    loadingImageV = UIImageView()
    contentV.addSubview(loadingImageV)
    loadingImageV.image = UIImage(named: "refresh-icon")
    
    loadingLabel = UILabel()
    contentV.addSubview(loadingLabel)
    loadingLabel.font = GlobalConfig.system15Font
    loadingLabel.textColor = GlobalConfig.BGSkyBlueColor
    loadingLabel.text = "努力加载中..."
    
  }
  
}


